import { onMounted, onUnmounted } from 'vue'

/**
 * 键盘快捷键配置
 */
export interface KeyboardShortcut {
  key: string
  ctrl?: boolean
  alt?: boolean
  shift?: boolean
  meta?: boolean
  callback: () => void
  description?: string
}

/**
 * 检查是否匹配快捷键
 */
function isMatchingShortcut(event: KeyboardEvent, shortcut: KeyboardShortcut): boolean {
  const keyMatches = event.key.toLowerCase() === shortcut.key.toLowerCase()
  const ctrlMatches = !!shortcut.ctrl === (event.ctrlKey || event.metaKey) // Mac上Cmd键对应ctrlKey
  const altMatches = !!shortcut.alt === event.altKey
  const shiftMatches = !!shortcut.shift === event.shiftKey
  const metaMatches = !!shortcut.meta === event.metaKey
  
  return keyMatches && ctrlMatches && altMatches && shiftMatches && metaMatches
}

/**
 * 格式化快捷键显示文本
 */
export function formatShortcutText(shortcut: KeyboardShortcut): string {
  const parts: string[] = []
  
  // 检测操作系统
  const isMac = /Mac|iPod|iPhone|iPad/.test(navigator.platform)
  
  if (shortcut.ctrl) {
    parts.push(isMac ? '⌘' : 'Ctrl')
  }
  if (shortcut.alt) {
    parts.push(isMac ? '⌥' : 'Alt')
  }
  if (shortcut.shift) {
    parts.push('⇧')
  }
  if (shortcut.meta && !isMac) {
    parts.push('Win')
  }
  
  parts.push(shortcut.key.toUpperCase())
  
  return parts.join(' + ')
}

/**
 * 键盘快捷键组合式函数
 */
export function useKeyboard(shortcuts: KeyboardShortcut[] = []) {
  const registeredShortcuts = new Map<string, KeyboardShortcut>()
  
  // 处理键盘事件
  const handleKeyDown = (event: KeyboardEvent) => {
    // 如果焦点在输入框内，忽略快捷键
    const target = event.target as HTMLElement
    if (target.tagName === 'INPUT' || 
        target.tagName === 'TEXTAREA' || 
        target.contentEditable === 'true') {
      return
    }
    
    // 检查是否匹配任何已注册的快捷键
    for (const shortcut of registeredShortcuts.values()) {
      if (isMatchingShortcut(event, shortcut)) {
        event.preventDefault()
        event.stopPropagation()
        shortcut.callback()
        break
      }
    }
  }
  
  // 注册快捷键
  const registerShortcut = (shortcut: KeyboardShortcut) => {
    const key = `${shortcut.key}-${shortcut.ctrl}-${shortcut.alt}-${shortcut.shift}-${shortcut.meta}`
    registeredShortcuts.set(key, shortcut)
  }
  
  // 取消注册快捷键
  const unregisterShortcut = (shortcut: KeyboardShortcut) => {
    const key = `${shortcut.key}-${shortcut.ctrl}-${shortcut.alt}-${shortcut.shift}-${shortcut.meta}`
    registeredShortcuts.delete(key)
  }
  
  // 初始化注册传入的快捷键
  shortcuts.forEach(registerShortcut)
  
  // 组件挂载时添加事件监听
  onMounted(() => {
    document.addEventListener('keydown', handleKeyDown)
  })
  
  // 组件卸载时移除事件监听
  onUnmounted(() => {
    document.removeEventListener('keydown', handleKeyDown)
    registeredShortcuts.clear()
  })
  
  return {
    registerShortcut,
    unregisterShortcut,
    formatShortcutText
  }
}

/**
 * 预定义常用快捷键
 */
export const COMMON_SHORTCUTS = {
  NEW: { key: 'n', ctrl: true, description: '新建' },
  SAVE: { key: 's', ctrl: true, description: '保存' },
  DELETE: { key: 'Delete', description: '删除' },
  ESCAPE: { key: 'Escape', description: '取消' },
  ENTER: { key: 'Enter', description: '确认' },
  SEARCH: { key: 'f', ctrl: true, description: '搜索' },
} as const